<template>
    <div class="login-container">
        <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="100px">
            <h2 class="title">登录</h2>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleLogin" :loading="loginButtonLoading">
                    {{ loginButtonText }}
                </el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { useCookies } from "vue3-cookies";
import useStore from "@/store/index";
import userAPI from "@/api/user";
import dictAPI from "@/api/dict/list";
import { md5 } from "@/utils/MD5";
import { errorNotify } from '@/utils/Misc';

const { cookies } = useCookies();
const router = useRouter();
const store = useStore();
const loginForm = ref({
    username: "",
    password: "",
});
const loginFormRef = ref(null);
const rules = {
    username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};
const loginButtonLoading = ref(false);
const loginButtonText = ref("登录");
const handleLogin = () => {
    loginFormRef.value.validate((valid) => {
        if (valid) {
            login();
        }
    });
};
const login = async () => {
    try {
        loginButtonLoading.value = true;
        loginButtonText.value = "登录中...";
        const loginParams = {
            username: loginForm.value.username,
            password: md5(loginForm.value.password),
        };
        const userRes = await userAPI.login(loginParams);
        const { token, ...user } = userRes.data.sysUser;
        cookies.set("token", token);
        store.setUser(user);
        const dictRes = await dictAPI.getTree();
        store.setDict(dictRes.data.dictTree);
        router.push("/dashboard");
    } catch (error) {
        if (error?.response?.data?.msg == "账号或密码错误") {
            return
        }
        errorNotify("Login.vue", "login", error);
    }
};
</script>
<style scoped>
.login-container {
    width: 300px;
    margin: 100px auto;
    padding: 20px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.title {
    text-align: center;
    margin-bottom: 20px;
}
</style>
